package com.soap.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.soap.commons.ReturnCommons;
import com.soap.entity.po.PermissionRouting;
import com.soap.entity.po.UserPermission;
import com.soap.manager.PermissionRoutingManager;
import com.soap.manager.UserPermissionManager;
import com.soap.service.UserPermissionService;
import com.soap.utils.JedisTools;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;

/**
 * @Description
 * @Author ZhangPY
 * @Date 2020/6/15
 */
@Service
@Slf4j(topic = "UserPermissionServiceImpl")
public class UserPermissionServiceImpl implements UserPermissionService {

    @Autowired
    private UserPermissionManager userPermissionManager;

    @Autowired
    private PermissionRoutingManager permissionRoutingManager;

    @Autowired
    private JedisTools jedisTools;

    @Override
    public String getUserPermissions(Long userId) {

        if (userId == null) {

            return ReturnCommons.getFail();
        }
        /** 先判断redis中是否有数据 **/
        String dataS = jedisTools.get(userId.toString());
        if (StringUtils.isNotBlank(dataS)) {
            Map map = JSONObject.parseObject(dataS, Map.class);
            return ReturnCommons.getSuccess(map);
        }
        Map<String, Object> data = null;

        String setNxUUID = UUID.randomUUID().toString();
        String setNxKey = "UserPermissions_"+ userId;
        /** 获取分布式锁 **/
        boolean setNx = jedisTools.setNx(setNxKey, setNxUUID, 20);

        if (setNx) {
            String dataSS = jedisTools.get(userId.toString());
            if (StringUtils.isNotBlank(dataSS)) {
                Map map = JSONObject.parseObject(dataSS, Map.class);
                return ReturnCommons.getSuccess(map);
            }

            /** 查询id对应的权限id **/
            QueryWrapper<UserPermission> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            List<UserPermission> list = userPermissionManager.list(wrapper);
            List<String> routerList = new ArrayList<>();
            List<Long> permissionId = new ArrayList<>();
            for (UserPermission userPermission : list) {
                permissionId.add(userPermission.getPermissionId());
            }
            List<Map<String, Object>> tree = new ArrayList<>();
            if (permissionId.size() > 0) {
                /** 根据权限id,查询出具体的资源id **/
                QueryWrapper<PermissionRouting> wrapperPer = new QueryWrapper<>();
                wrapperPer.in("id", permissionId);
                List<PermissionRouting> listPer = permissionRoutingManager.list(wrapperPer);
                for (PermissionRouting permissionRouting : listPer) {
                    routerList.add(permissionRouting.getUrl());
                }

                tree = getTree((long) 0, listPer);

            }
            data = new HashMap<>();
            data.put("tree", tree);
            data.put("routers", routerList);
            log.error("查询了数据库");
            boolean setex = jedisTools.setex(userId.toString(), JSONObject.toJSONString(data), 60);

            if (setex) {
                /** 插入成功 , 进行分布式解锁 **/
                jedisTools.setNxUnLock(setNxKey , setNxUUID);
            }
        }

        return ReturnCommons.getSuccess(data);
    }


    @Override
    public String getUserPermissionsList(Long userId) {
        if (userId == null) {
            return ReturnCommons.getFail();
        }

        /** 查询id对应的权限id **/
        QueryWrapper<UserPermission> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<UserPermission> list = userPermissionManager.list(wrapper);
        List<Long> userPermissionId = list.stream().map(u -> u.getPermissionId()).collect(Collectors.toList());
        Map<String, Object> data = new HashMap<>();
        data.put("userPermissionId", userPermissionId);
        return ReturnCommons.getSuccess(data);

    }


    @Transactional
    @Override
    public String updateUserPermissions(Long userId, String permissionsId) {
        if (userId == null) {
            return ReturnCommons.getFail();
        }
        /** 删除原有的权限 **/
        QueryWrapper<UserPermission> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id" , userId);
        userPermissionManager.remove(wrapper);

        if (StringUtils.isBlank(permissionsId)) {
            return ReturnCommons.getSuccess();
        }
        String[] split = permissionsId.split(",");
        List<Long> pId = new ArrayList<>();
        for (String s : split) {
            pId.add(Long.valueOf(s));
        }

        /** 赋值新的权限 **/
        List<UserPermission> userPermissionList = pId.stream().map(p -> new UserPermission().setUserId(userId).setPermissionId(p)).collect(Collectors.toList());
        boolean saveBatch = userPermissionManager.saveBatch(userPermissionList);

        if (saveBatch) {
            return ReturnCommons.getSuccess();
        } else {
            return ReturnCommons.getFail();
        }
    }

    private List<Map<String,Object>> getTree(Long parentId , List<PermissionRouting> allList){
        /** 用于保存子节点的list **/
        List<Map<String,Object>> childList = new ArrayList<>();
        for(PermissionRouting permissionRouting : allList){
            /** 判断传入id是否等于自身的父级id，如果是，就说明自己是子节点 **/
            if(permissionRouting != null && parentId.equals(permissionRouting.getParentId())){
                Map<String,Object> map = new HashMap<>();
                map.put("id",permissionRouting.getId());
                map.put("parentId", permissionRouting.getParentId());
                map.put("label",permissionRouting.getName());
                map.put("url",permissionRouting.getUrl());
                map.put("type",permissionRouting.getType());
                map.put("icon",permissionRouting.getIcon());
                map.put("children", new Object[]{});
                map.put("hasChildren",false);
                /** 加入子节点 **/
                childList.add(map);
            }
        }
        /** 遍历子节点，继续递归判断每个子节点是否还含有子节点 **/
        for(Map<String,Object> map : childList){
            List<Map<String,Object>> tList = getTree(Long.valueOf(map.get("id").toString())  , allList);
            if(!tList.isEmpty()){
                map.put("hasChildren",true);
            }
            map.put("children" , tList);
        }
        return childList;
    }
}
